package com.blb.bulletscreen;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;

/**
 * 弹幕服务器处理器
 */
public class BulletScreenServerHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    //通道组
    private static ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    //客户端连接
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().remoteAddress()+"连接");
        channels.add(ctx.channel());
    }

    //客户端断开
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().remoteAddress()+"断开");
        channels.remove(ctx.channel());
    }

    //读取弹幕消息
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame frame) throws Exception {
        String msg = frame.text();
        System.out.println(ctx.channel().remoteAddress()+ ":" + msg);
        //群发
        channels.writeAndFlush(new TextWebSocketFrame(ctx.channel().remoteAddress()+ ":" + msg));
    }

    //客户端异常
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
        channels.remove(ctx.channel());
    }
}
